import {Component, OnInit} from '@angular/core';
import {PageEntity} from '../../../core/domain/page.entity';
import {StatusEnum} from '../../../core/enum/status.enum';
import {NzMessageService} from 'ng-zorro-antd';
import {PaginationUtils} from '../../../utils/paginationUtils';
import {StorageUtil} from '../../../utils/storage.util';
import {OtherUtil} from '../../../utils/other.util';
import { DepartmentEvaluteService } from './department-evaluate.service';
import {FilterEnum} from '../../../core/enum/filter.enum';
import {HTTP_BASE_URL, SERVERS_NAME} from '../../../config/config';
import { PostDown } from '../../../utils/postdown';

declare var $: any;

@Component({
  selector: 'app-department-evaluate',
  templateUrl: './department-evaluate.component.html',
  styleUrls: ['./department-evaluate.component.scss'],
  providers: [DepartmentEvaluteService,PostDown]
})
/**********系部评价统计*************/
export class DepartmentEvaluateComponent implements OnInit {
  pageInfo: PageEntity = new PageEntity();
  pageInfo2: PageEntity = new PageEntity();
  mainStatus = 1; // 1.显示主页面，2.显示评价列表,3:显示详情页面
  dataList = [];
  allList = [];
  nzWidthConfigs = [];
  searchParams: SearchParams = new SearchParams();
  memberParams: MemberParams = new MemberParams();
  yearList = [];
  semestSearch = [];
  view = false;
  evaluateTableObj: EvaluateTableObj = new EvaluateTableObj();
  evaluateObj: any = {};
  assessmentPersonArr = [
    {label: '学院领导', value: '学院领导', checked: false},
    {label: '督导员', value: '督导员', checked: false},
    {label: '系部负责人', value: '系部负责人', checked: false},
    {label: '职能部门负责人', value: '职能部门负责人', checked: false},
  ];
  displayList: Array<any> = [];
  mapOfCheckedId: { [key: string]: boolean } = {};
  isAllCheck = false;
  isIndeterminate = false;
  canDelete = false;
  checkerRole = [];
  evaluateProjectList = [];
  evaluateProjectNoScoreList = [];
  rowSpanIndexArr = [];
  tdHiddenIndexArr = [];
  totalScore = 0;
  uploadUrl = `${SERVERS_NAME.UPLOAD_URL}`;
  headerInfo = null;
  linkInfo = `${HTTP_BASE_URL}${SERVERS_NAME.SECURITY_SERVER}`;
  pictureArr = ['png', 'jpg', 'jpeg', 'bmg', 'gif'];
  previewVisible = false;
  previewImage: string | undefined = '';
  fileList = [];
  constructor(
    private http: DepartmentEvaluteService,
    private message: NzMessageService,
    private postDown: PostDown
  ) { }

  ngOnInit() {
    this.headerInfo = StorageUtil.getFileHeader();
    this.getYearSearch();
    this.page(this.pageInfo);
  }

  /**
   * 查询学年学期列表
   */
   getYearSearch() {
    this.http.year().subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.yearList = res.datas;
        this.semestSearch = [];
      }
    });
  }

  yearSearchChange(e) {
    this.searchParams.semesterId = null;
    this.yearList.forEach(item => {
      if (e == item.schoolYear) {
        this.semestSearch = item.semester;
      }
    });
  }


  page(page) {
    this.pageInfo.filters.type = PaginationUtils.filters('系部督导', FilterEnum.EQUALS);
    this.pageInfo.multiSortMeta = [
      {
        field: 'gmtCreate',
        order: -1
      }
    ];
    this.http.page(page).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.dataList = res.datas.data;
        this.pageInfo.totalRecords = res.datas.totalRecords;
        // this.nzWidthConfigs = ['60px', '100px', '100px', '150px', '200px', '100px', '100px', '180px', '100px', '100px', '100px', '150px',
        // '120px', '120px', '180px', '200px', '110px', '110px'];
        this.nzWidthConfigs = ['60px', '100px', '100px', '150px', '200px', '100px', '100px', '180px', '100px', '100px', '100px', '180px', '200px', '110px', '110px'];
      }
    });
  }

  /**
   * 点击查询
   */
  clickSearch() {
    for (const o in this.searchParams) {
      if (this.searchParams[o]) {
        this.pageInfo.filters[o] = PaginationUtils.filters(this.searchParams[o], FilterEnum.CONTAINS);
      } else {
        delete this.pageInfo.filters[o];
      }
      if (this.searchParams.semesterId) {
        this.pageInfo.filters.semesterId = PaginationUtils.filters(this.searchParams.semesterId, FilterEnum.EQUALS);
      }
    }
    this.pageInfo.first = 1;
    this.page(this.pageInfo);
  }

  /**
   * 点击重置
   */
  resetSearch() {
    this.searchParams = new SearchParams();
    this.pageInfo = new PageEntity();
    this.clickSearch();
  }

  changePageIndex(index) {
    this.pageInfo.first = index;
    this.page(this.pageInfo);
  }

  changePageSize(size) {
    this.pageInfo.first = 1;
    this.pageInfo.rows = size;
    this.clickSearch();
  }

  currentPageDataChange($event): void {
    console.log($event)
    this.displayList = $event;
    this.refreshStatus();
  }

  /**
 * 全选
 * @param value： value
 */
   checkAll(value: boolean): void {
    this.displayList.forEach(item => (this.mapOfCheckedId[item.id] = value));
    this.refreshStatus();
  }

  /*******状态改变******/
  refreshStatus(): void {
    this.isAllCheck = this.displayList.every(item => this.mapOfCheckedId[item.id]);
    this.isIndeterminate =
      this.displayList.some(item => this.mapOfCheckedId[item.id]) &&
      !this.isAllCheck;
    this.checkDelete();
  }

  /********判断是否选择了数据需要删除**********/
  checkDelete(): void {
    this.canDelete = OtherUtil.deleteIds(this.mapOfCheckedId).length <= 0;
  }

  /**
   * 点击查询
   */
   clickSearch2() {
    for (const o in this.memberParams) {
      if (this.memberParams[o]) {
        this.pageInfo2.filters[o] = PaginationUtils.filters(this.memberParams[o], FilterEnum.CONTAINS);
      } else {
        delete this.pageInfo2.filters[o];
      }
    }
    this.pageInfo2.first = 1;
    this.pageList(this.pageInfo2);
  }

  /**
   * 点击重置
   */
  resetSearch2() {
    this.memberParams = new MemberParams();
    delete this.pageInfo2.filters['checkerRole'];
    delete this.pageInfo2.filters['checker'];
    this.clickSearch2();
  }

  changePageIndex2(index) {
    this.pageInfo2.first = index;
    this.clickSearch2();
  }

  changePageSize2(size) {
    this.pageInfo2.first = 1;
    this.pageInfo2.rows = size;
    this.clickSearch2();
  }

  /**
   * 点击删除一个
   * @param ids： id
   */
  deleteOne(id: string) {
    this.http.delete({id:id}).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.message.success(res.message);
        this.page(this.pageInfo);
      }
    });
  }

  /**
   * 点击切换选中tab
   */
  changeTab(data) {
    if (data.value === this.searchParams.state) { return false; }
    this.pageInfo = new PageEntity();
    this.searchParams = new SearchParams();
    this.searchParams.state = data.value;
    this.clickSearch();
  }

  /**
   * 点击评价
   */
  clickEvaluated(data) {
    this.mainStatus = 3
    this.http.getEvaluateApi({
      id: data.id
    }).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.evaluateObj = res.datas;
        this.evaluateProjectList = [];
        this.evaluateProjectNoScoreList = [];
        this.rowSpanIndexArr = [];
        this.tdHiddenIndexArr = [];
        this.totalScore = this.evaluateObj.score;
        this.checkerRole = res.datas.checkerRole.split(',');
        this.assessmentPersonArr.map(item => {
          item.checked = this.checkerRole.includes(item.value);
        });
        this.fileList = [];
        this.checkerRole = [];
        this.evaluateTableObj = new EvaluateTableObj();
        (res.datas.classifyList || []).map(item => {
          if (item.itemList) {
            (item.itemList || []).map(ele => {
              this.evaluateProjectList.push({
                rowInfo: { ...ele },
                ...item
              });
            });
          } else {
            // 无分数
            if(!item.examClassifyScore) {
              this.evaluateProjectNoScoreList.push({
                rowInfo: item,
                ...item
              });
            } else {
              // 有分数
              this.evaluateProjectList.push({
                rowInfo: { ...{} },
                ...item
              });
            }
          }
        });

        let totalNum = 0;
        this.evaluateProjectList.map((item, index) => {
          if (totalNum === index) {
            console.log(item)
            if(item.itemList) {
              this.rowSpanIndexArr.push(item.itemList.length);
              totalNum += item.itemList.length;
            } else {
              this.rowSpanIndexArr.push(1);
              totalNum +=1
            }
            this.tdHiddenIndexArr.push(totalNum);
          } else {
            this.rowSpanIndexArr.push(index);
          }
        });
        this.tdHiddenIndexArr.unshift(0);
      }
    });
  }

  /**
   * 选择课评人员
   */
  changeAssessment(value) {
    this.checkerRole = [];
    value.map(item => {
      if (item.checked) {
        this.checkerRole.push(item.value);
      }
    });
  }

  /**
   * 点击详情
   */
   edit(id: string) {
    this.mainStatus = 2
    this.pageInfo2.filters.examCourseId = PaginationUtils.filters(id, FilterEnum.EQUALS);
    this.pageList(this.pageInfo2)
  }
  pageList(page) {
    page.multiSortMeta = [
      {
        field: 'gmtModified',
        order: -1
      }
    ];
    this.http.pageEvalute(page).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.allList = res.datas.data;
        this.pageInfo2.totalRecords = res.datas.totalRecords;
      }
    });
  }
  /**
   * 下载
   * @param id:id
   */
  downLoad(id:string) {
    console.log(id)
    window.open(`${HTTP_BASE_URL}security-server/dietc/sys/source/download/` + id);
  }

  /**
   * 预览图片
   * @param item 数据像
   */
  previewImg(item) {
    const suffixName = item.fileOriginalName.slice(item.fileOriginalName.lastIndexOf('.') + 1);
    if (this.pictureArr.includes(suffixName)) {
      this.previewVisible = true;
      this.previewImage = this.linkInfo + 'source/view/' + item.moduleName + '/' + item.fileNewName;
    } else {
      // @ts-ignore
      window.location = this.linkInfo + 'source/view/' + item.moduleName + '/' + item.fileNewName;
    }
  }
  /**
   * 1：导出选中；2：导出当前页；3：导出全部
   */
   exportShow(num: number): void {
    const obj = {
      mode: num,
      pager: {},
      sourceIds: []
    };
    if (num === 1) {
      const arr = this.delByIdsLogic();
      if (arr.length < 1) {
        this.message.warning('请勾选要导出的数据！');
        return;
      }
      obj.pager = this.pageInfo2;
      obj.sourceIds = Object.keys(this.mapOfCheckedId).filter(k => this.mapOfCheckedId[k] === true);
    } else if (num === 3) {
      obj.pager = this.pageInfo2;
      obj.sourceIds = [];
    }
    this.postDown.postDownload('evalute-server/evalute/evalute/superviseExam/exportEvaluteExcel', obj);
  }
  /**
   * 主页根据id删除逻辑
   */
   delByIdsLogic() {
    const arr = [];
    for (const val in this.mapOfCheckedId) {
      if (this.mapOfCheckedId[val]) {
        arr[arr.length] = val;
      }
    }
    return arr;
  }
  // 返回上一级
  back(num) {
    this.mainStatus = num;
    this.mapOfCheckedId = {};
    if(num == 2) {
      this.pageList(this.pageInfo2)
    }
  }
}

class SearchParams {
  schoolYear: string;
  semesterId: any;
  number: string;
  name: string;
  teacherName: string;
  classesName: string;
  state: any = '';
}

class MemberParams {
  checker: string;
  checkerRole: string;
}

class EvaluateTableObj {
  evaluteDate: string;
  startSection: number;
  endSection: number;
  shouldCount = 0;
  realCount = 0;
  lateCount = 0;
  missCount = 0;
  content: string;
  sourceIdList: any;
  courseId: string;
  courseName: string;
}
